package thread.demo.countDownLatch;

import java.util.concurrent.*;

public class CountDownLatchTest001 {
  
  static ExecutorService executorService = Executors.newFixedThreadPool(3);
  static CountDownLatch countDownLatch = new CountDownLatch(3);
  
  public static void main(String[] args) throws InterruptedException {
    System.out.println("开始执行 main task ...");
    long start = System.currentTimeMillis();
    
    executorService.execute(CountDownLatchTest001::task01);
    executorService.execute(CountDownLatchTest001::task02);
    executorService.execute(CountDownLatchTest001::task03);
    
    countDownLatch.await();
    
    System.out.println(System.currentTimeMillis() - start);
    System.out.println("结束执行 main task ...");
  }
  
  public static void task01() {
    System.out.println("task01 开始任务...");
    sleep(1);
    System.out.println("task01 结束任务...");
    countDownLatch.countDown();
  }
  
  public static void task02() {
    System.out.println("task02 开始任务 ...");
    sleep(2);
    System.out.println("task02 结束任务 ...");
    countDownLatch.countDown();
  }
  
  public static void task03() {
    System.out.println("task03 开始任务 ...");
    sleep(3);
    System.out.println("task03 结束任务 ...");
    countDownLatch.countDown();
  }
  
  public static void sleep(long time) {
    try {
      TimeUnit.SECONDS.sleep(time);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
}
